package com.gua.encrypt.config;

import java.nio.charset.StandardCharsets;

import javax.annotation.Resource;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import com.gua.common.exception.BusinessExecption;
import com.gua.encrypt.constants.CryptoConstant;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.symmetric.AES;

/**
 * https://gitee.com/springboot-hlh/spring-boot-csdn/tree/master/09-spring-boot-interface-crypto
 * 
 * @author huangjj
 * @description: 自动配置类
 */
@ConditionalOnProperty(prefix = "crypto", name = "type", havingValue = CryptoConstant.TYPE_AES, matchIfMissing = false)
@Configuration
public class AESCryptConfig {

	@Resource
	private AESCryptProperties aesCryptProperties;

	@Bean
	public AES aes() {
		String key = Base64.decodeStr(aesCryptProperties.getKey());
		String iv = Base64.decodeStr(aesCryptProperties.getIv());
		if(aesCryptProperties.getMode()==null 
			|| aesCryptProperties.getPadding()==null
			|| StringUtils.isEmpty(key)
			|| StringUtils.isEmpty(iv)) {
			throw new BusinessExecption(String.format("加密类型%s配置为aes时，AES配置不能为空：%s, %s, %s, %s", 
					"crypto.type", 
					"crypto.aes.mode", 
					"crypto.aes.padding", 
					"crypto.aes.key", 
					"crypto.aes.vi"));
		}
		if(StringUtils.isEmpty(key) || StringUtils.isEmpty(iv)) {
			throw new BusinessExecption(String.format("AES配置有误：%s, %s", 
					 "crypto.aes.key", "crypto.aes.vi"));
		}
		return new AES(aesCryptProperties.getMode(), 
				aesCryptProperties.getPadding(),
				key.getBytes(StandardCharsets.UTF_8),
				iv.getBytes(StandardCharsets.UTF_8));
	}

}
